/*
 * GTFSShapes.java
 * 
 * Created by demory on Jul 6, 2009, 9:04:39 PM
 * 
 * Copyright 2008 David D. Emory
 * 
 * This file is part of Five Points. See <http://www.fpdev.org> for
 * additional information regarding the project.
 * 
 * Five Points is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Five Points is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Five Points.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.fpdev.core.transit.gtfs;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.MultiLineString;
import java.awt.geom.Point2D;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.FeatureWriter;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

/**
 *
 * @author demory
 */
public class GTFSShapes extends GTFSDBTable {

  private Map<String, SortedMap<Integer, Point2D>> shapeMap_;

  public GTFSShapes(File file, GTFSImporter importer) {
    super("shapes", file, importer);
    shapeMap_ = new HashMap<String, SortedMap<Integer, Point2D>>();
  }

  public void initShapes() {
    int shpCol = columnNames_.get("shape_id");
    int latCol = columnNames_.get("shape_pt_lat");
    int lonCol = columnNames_.get("shape_pt_lon");
    int seqCol = columnNames_.get("shape_pt_sequence");


    for(String[] row : getData()) {
      String shpID = row[shpCol];
      
      if(!shapeMap_.containsKey(shpID)) shapeMap_.put(shpID, new TreeMap<Integer, Point2D>());
      SortedMap<Integer, Point2D> pts = shapeMap_.get(shpID);

      double lat = new Double(row[latCol]), lon = new Double(row[lonCol]);
      pts.put(new Integer(row[seqCol]), new Point2D.Double(lon, lat));

    }
  }

  public SortedMap<Integer, Point2D> getShape(String id) {
    int shpCol = columnNames_.get("shape_id");
    int latCol = columnNames_.get("shape_pt_lat");
    int lonCol = columnNames_.get("shape_pt_lon");
    int seqCol = columnNames_.get("shape_pt_sequence");

    SortedMap<Integer, Point2D> pts = new TreeMap<Integer, Point2D>();

    for(String[] row : getData("shape_id = \""+id+"\"")) {
      double lat = new Double(row[latCol]), lon = new Double(row[lonCol]);
      pts.put(new Integer(row[seqCol]), new Point2D.Double(lon, lat));
    }
    
    return pts;
    //return shapeMap_.get(id);
  }



  public void createShapefile() {
    // test -- create shapefile
    try {

      File file = new File("/home/demory/5p/shp/gtfsrtes.shp");
      if(!file.exists()) file.createNewFile();

      // create the datastore
      ShapefileDataStore outStore = new ShapefileDataStore(file.toURI().toURL());

      // initialize the CRS
      //CoordinateReferenceSystem crs = CRS.decode(crsCode);
      //System.out.println("crs: "+crs.getName());
      //outStore.forceSchemaCRS(crs);


      SimpleFeatureType featureType = DataUtilities.createType("gtfsrtes", "geom:MultiLineString,shpid:String");
      outStore.createSchema(featureType);

      Transaction transaction = new DefaultTransaction("handle");

      FeatureWriter writer = outStore.getFeatureWriter(outStore.getTypeNames()[0], transaction);//Transaction.AUTO_COMMIT);

      // POPULATE THE DATA

      GeometryFactory gf = new GeometryFactory();
      for(Map.Entry<String, SortedMap<Integer, Point2D>> entry : shapeMap_.entrySet()) {

        Coordinate[] coords = new Coordinate[entry.getValue().size()];
        int i = 0;
        for(Point2D pt : entry.getValue().values()) {
          coords[i] = new Coordinate(pt.getX(), pt.getY());
          i++;
        }
        LineString line = gf.createLineString(coords);
        LineString[] lines = new LineString[1];
        lines[0] = line;

        MultiLineString multi = gf.createMultiLineString(lines);

        SimpleFeature feature = (SimpleFeature) writer.next();
        feature.setDefaultGeometry(multi);
        feature.setAttribute("shpid", entry.getKey());

        writer.write();
      }
      // WRITE TO DATASTORE

      writer.close();
      transaction.commit();
      transaction.close();


      System.out.println("GTFS-Routes shapefile written");

    } catch(Exception e) {
      e.printStackTrace();
    }
  }

}
